<template>
  <Header></Header>
  
  <div class="container mx-auto px-4 py-8 bg-gradient-to-b from-blue-50 to-white">
    <!-- 轮播图 -->
    <div class="mb-12">
      <el-carousel :interval="4000" type="card" height="300px" class="rounded-lg overflow-hidden">
        <el-carousel-item v-for="(article, index) in featuredArticles" :key="index" class="relative">
          <div @click="goToArticle(article.id)" class="cursor-pointer h-full w-full">
            <img :src="article.cover || article.titleImage || article.title_image || 'https://via.placeholder.com/800x400?text=热门文章'" 
                 class="w-full h-full object-cover" alt="热门文章封面">
            <div class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-indigo-900/80 to-transparent p-4">
              <h3 class="text-white text-xl font-bold line-clamp-2">{{ article.title }}</h3>
              <p class="text-white/80 text-sm mt-2 line-clamp-2">{{ article.summary || '点击查看详情' }}</p>
              <div class="flex items-center mt-2 space-x-3 text-white/70 text-xs">
                <span v-if="article.favoriteCount && article.favoriteCount > 0" class="flex items-center">
                  <svg class="w-4 h-4 mr-1 text-pink-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                      d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"/>
                  </svg>
                  {{ article.favoriteCount }}
                </span>
                <span v-if="article.readNum && article.readNum > 0" class="flex items-center">
                  <svg class="w-4 h-4 mr-1 text-blue-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                      d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"/>
                  </svg>
                  {{ article.readNum }} 阅读
                </span>
                <span>{{ formatDate(article.createTime) }}</span>
              </div>
            </div>
          </div>
        </el-carousel-item>
      </el-carousel>
    </div>

    <h1 class="text-3xl font-bold mb-8 text-center text-indigo-800 relative">
      <span class="relative z-10">热门内容</span>
      <span class="absolute left-1/2 -translate-x-1/2 bottom-1 w-24 h-2 bg-yellow-300 opacity-50 rounded-full"></span>
    </h1>

    <!-- 主要内容区域：左侧热门文章，右侧标签和分类 -->
    <div class="flex flex-col lg:flex-row gap-8">
      <!-- 左侧：热门文章 -->
      <div class="w-full lg:w-2/3">
        <div class="flex items-center justify-between mb-4">
          <h2 class="text-2xl font-semibold text-indigo-700">热门文章</h2>
          <div class="flex space-x-2">
            <button 
              @click="sortBy = 'favorites'" 
              :class="{'bg-indigo-600 text-white': sortBy === 'favorites', 'bg-gray-100 text-gray-700 hover:bg-indigo-100': sortBy !== 'favorites'}"
              class="px-3 py-1 text-sm rounded-full transition-colors duration-200"
            >
              收藏量
            </button>
            <button 
              @click="sortBy = 'likes'" 
              :class="{'bg-indigo-600 text-white': sortBy === 'likes', 'bg-gray-100 text-gray-700 hover:bg-indigo-100': sortBy !== 'likes'}"
              class="px-3 py-1 text-sm rounded-full transition-colors duration-200"
            >
              点赞量
            </button>
            <button 
              @click="sortBy = 'comments'" 
              :class="{'bg-indigo-600 text-white': sortBy === 'comments', 'bg-gray-100 text-gray-700 hover:bg-indigo-100': sortBy !== 'comments'}"
              class="px-3 py-1 text-sm rounded-full transition-colors duration-200"
            >
              评论量
            </button>
          </div>
        </div>

        <div v-if="loading.articles" class="flex justify-center py-10">
          <el-skeleton :rows="5" animated />
        </div>

        <div v-else-if="popularArticles.length === 0" class="text-center py-10 text-gray-500">
          暂无热门文章
        </div>

        <div v-else class="grid md:grid-cols-2 gap-6">
          <div v-for="article in popularArticles" :key="article.id" 
               class="bg-white rounded-lg shadow-md overflow-hidden transition-all duration-300 hover:shadow-lg hover:-translate-y-1 hover:shadow-indigo-100 border border-indigo-50">
            <div class="h-48 bg-indigo-50 relative overflow-hidden">
              <img v-if="article.cover || article.titleImage || article.title_image" :src="article.cover || article.titleImage || article.title_image" :alt="article.title" class="w-full h-full object-cover">
              <div v-else class="h-full flex items-center justify-center bg-gradient-to-br from-indigo-50 to-blue-100">
                <svg class="w-12 h-12 text-indigo-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                        d="M19 20H5a2 2 0 01-2-2V6a2 2 0 012-2h10a2 2 0 012 2v1M19 20a2 2 0 002-2V8a2 2 0 00-2-2h-5M5 14l3-3 3 3m4 0l3-3 3 3"/>
                </svg>
              </div>
            </div>
            <div class="p-4">
              <h3 class="text-lg font-semibold text-gray-800 mb-2 line-clamp-2 hover:text-indigo-600 transition-colors cursor-pointer" @click="goToArticle(article.id)">{{ article.title }}</h3>
              <p class="text-sm text-gray-500 mb-3 line-clamp-2">{{ article.summary || getDefaultSummary(article) }}</p>
              <div class="flex items-center justify-between text-xs text-gray-500">
                <span class="text-indigo-500">{{ formatDate(article.createTime) }}</span>
                <div class="flex items-center space-x-3">
                  <span v-if="article.favoriteCount && article.favoriteCount > 0" class="flex items-center">
                    <svg class="w-4 h-4 mr-1 text-pink-500" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                            d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"/>
                    </svg>
                    {{ article.favoriteCount }}
                  </span>
                  <span v-if="article.likeCount && article.likeCount > 0" class="flex items-center">
                    <svg class="w-4 h-4 mr-1 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                            d="M14 10h4.764a2 2 0 011.789 2.894l-3.5 7A2 2 0 0115.263 21h-4.017c-.163 0-.326-.02-.485-.06L7 20m7-10V5a2 2 0 00-2-2h-.095c-.5 0-.905.405-.905.905 0 .714-.211 1.412-.608 2.006L7 11v9m7-10h-2M7 20H5a2 2 0 01-2-2v-6a2 2 0 012-2h2.5"/>
                    </svg>
                    {{ article.likeCount }}
                  </span>
                  <span class="flex items-center">
                    <svg class="w-4 h-4 mr-1 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 
                            d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z"/>
                    </svg>
                    {{ article.commentCount || 0 }}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧：热门标签和分类 -->
      <div class="w-full lg:w-1/3 space-y-6">
        <!-- 热门标签 -->
        <div class="bg-white rounded-lg shadow-md p-6 border-t-4 border-indigo-500">
          <h2 class="text-2xl font-semibold text-indigo-700 mb-4">热门标签</h2>
          
          <div v-if="loading.tags" class="py-4">
            <el-skeleton :rows="3" animated />
          </div>
          
          <div v-else-if="popularTags.length === 0" class="text-center py-4 text-gray-500">
            暂无热门标签
          </div>
          
          <div v-else class="flex flex-wrap gap-2">
            <router-link 
              v-for="tag in popularTags" 
              :key="tag.id"
              :to="`/tag/list?id=${tag.id}&name=${tag.name}`"
              class="px-3 py-1 bg-indigo-50 text-indigo-600 rounded-full text-sm hover:bg-indigo-100 transition-colors duration-200 flex items-center"
            >
              <span>{{ tag.name }}</span>
              <span class="ml-1 text-xs text-indigo-500/80">({{ tag.count }})</span>
            </router-link>
          </div>
        </div>

        <!-- 热门分类 -->
        <div class="bg-white rounded-lg shadow-md p-6 border-t-4 border-yellow-500">
          <h2 class="text-2xl font-semibold text-indigo-700 mb-4">热门分类</h2>
          
          <div v-if="loading.categories" class="py-4">
            <el-skeleton :rows="3" animated />
          </div>
          
          <div v-else-if="popularCategories.length === 0" class="text-center py-4 text-gray-500">
            暂无热门分类
          </div>
          
          <div v-else>
            <router-link 
              v-for="category in popularCategories" 
              :key="category.id"
              :to="`/category/list?id=${category.id}&name=${category.name}`"
              class="flex items-center justify-between p-2 border-b border-indigo-50 hover:bg-indigo-50 transition-colors duration-200 rounded"
            >
              <span class="text-gray-700">{{ category.name }}</span>
              <span class="bg-indigo-100 text-indigo-600 rounded-full px-2 py-0.5 text-xs">{{ category.count }} 篇文章</span>
            </router-link>
          </div>
        </div>
      </div>
    </div>
  </div>

  <Footer></Footer>
</template>

<script setup>
import { ref, reactive, onMounted, watch, computed } from 'vue';
import { useRouter } from 'vue-router';
import { getPopularArticles, getPopularTags, getPopularCategories } from '@/api/frontend/popular';
import Header from '@/layouts/components/Header.vue';
import Footer from '@/layouts/components/Footer.vue';

const router = useRouter();

const popularArticles = ref([]);
const popularTags = ref([]);
const popularCategories = ref([]);
const sortBy = ref('favorites'); // 默认按收藏量排序
const loading = reactive({
  articles: true,
  tags: true,
  categories: true
});

// 计算属性：从热门文章中获取前5篇用于轮播图
const featuredArticles = computed(() => {
  if (popularArticles.value.length > 0) {
    return popularArticles.value.slice(0, 5);
  }
  // 如果没有获取到真实数据，提供一些默认的轮播图数据
  return [
    {
      id: 1,
      title: '探索Vue3的组合式API',
      summary: 'Vue3的组合式API提供了更灵活的代码组织方式，本文详细介绍了如何使用ref、reactive、watch等函数...',
      cover: 'https://picsum.photos/800/400?random=1',
      createTime: new Date().toISOString(),
      favoriteCount: 78,
      readNum: 325
    },
    {
      id: 2,
      title: '前端工程化实践：从零搭建一个现代化的前端项目',
      summary: '本文将带你一步步搭建一个包含Vue3、TypeScript、Vite、ESLint等工具的现代化前端项目...',
      cover: 'https://picsum.photos/800/400?random=2',
      createTime: new Date().toISOString(),
      favoriteCount: 65,
      readNum: 287
    },
    {
      id: 3,
      title: '深入理解JavaScript的异步编程',
      summary: '从回调地狱到Promise，再到async/await，本文详细讲解了JavaScript异步编程的演进历程和各种技术的优缺点...',
      cover: 'https://picsum.photos/800/400?random=3',
      createTime: new Date().toISOString(),
      favoriteCount: 91,
      readNum: 412
    },
    {
      id: 4,
      title: '使用TailwindCSS构建响应式UI',
      summary: 'TailwindCSS是一个功能类优先的CSS框架，本文详细介绍了如何使用TailwindCSS快速构建美观的响应式UI...',
      cover: 'https://picsum.photos/800/400?random=4',
      createTime: new Date().toISOString(),
      favoriteCount: 53,
      readNum: 246
    },
    {
      id: 5,
      title: 'Web性能优化实战指南',
      summary: '本文提供了一系列实用的Web性能优化技巧，包括资源加载优化、渲染性能优化、代码优化等方面...',
      cover: 'https://picsum.photos/800/400?random=5',
      createTime: new Date().toISOString(),
      favoriteCount: 82,
      readNum: 368
    }
  ];
});

// 格式化日期的函数
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' });
};

// 添加一个获取默认摘要的函数
const getDefaultSummary = (article) => {
  if (article.content) {
    const plainText = article.content.replace(/<[^>]+>/g, '');
    return plainText.substring(0, 100) + (plainText.length > 100 ? '...' : '');
  }
  return '这篇文章很精彩，点击查看详情...';
};

// 获取热门文章
const fetchPopularArticles = async () => {
  loading.articles = true;
  try {
    const response = await getPopularArticles(sortBy.value);
    console.log('API返回的文章数据:', response); // 添加日志查看返回的数据结构
    
    if (response.success) {
      // 检查返回的数据中摘要字段的名称是否正确
      popularArticles.value = (response.data || []).map(article => {
        // 检查可能的摘要字段名称
        if (!article.summary && (article.abstract || article.description || article.excerpt)) {
          article.summary = article.abstract || article.description || article.excerpt;
        }
        return article;
      });
    }
  } catch (error) {
    console.error('获取热门文章失败:', error);
    // 模拟数据，实际项目中需要删除
    popularArticles.value = Array.from({ length: 6 }, (_, i) => ({
      id: i + 1,
      title: `热门文章标题 ${i + 1}`,
      summary: `这是热门文章 ${i + 1} 的摘要内容，介绍了文章的主要内容和亮点...`,
      createTime: new Date().toISOString(),
      favoriteCount: Math.floor(Math.random() * 100),
      likeCount: Math.floor(Math.random() * 200),
      commentCount: Math.floor(Math.random() * 50),
      cover: i % 2 === 0 ? `https://picsum.photos/500/300?random=${i}` : ''
    }));
  } finally {
    loading.articles = false;
  }
};

// 获取热门标签
const fetchPopularTags = async () => {
  loading.tags = true;
  try {
    const response = await getPopularTags();
    if (response.success) {
      popularTags.value = response.data || [];
    }
  } catch (error) {
    console.error('获取热门标签失败:', error);
    // 模拟数据，实际项目中需要删除
    popularTags.value = Array.from({ length: 10 }, (_, i) => ({
      id: i + 1,
      name: `标签${i + 1}`,
      count: Math.floor(Math.random() * 30) + 1
    }));
  } finally {
    loading.tags = false;
  }
};

// 获取热门分类
const fetchPopularCategories = async () => {
  loading.categories = true;
  try {
    const response = await getPopularCategories();
    if (response.success) {
      popularCategories.value = response.data || [];
    }
  } catch (error) {
    console.error('获取热门分类失败:', error);
    // 模拟数据，实际项目中需要删除
    popularCategories.value = Array.from({ length: 5 }, (_, i) => ({
      id: i + 1,
      name: `分类${i + 1}`,
      count: Math.floor(Math.random() * 50) + 5
    }));
  } finally {
    loading.categories = false;
  }
};

// 跳转到文章详情页
const goToArticle = (articleId) => {
  router.push(`/article/detail?articleId=${articleId}`);
};

// 监听排序方式变化，重新获取热门文章
watch(sortBy, () => {
  fetchPopularArticles();
});

onMounted(() => {
  fetchPopularArticles();
  fetchPopularTags();
  fetchPopularCategories();
});
</script>

<style scoped>
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.el-carousel__item {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
}

.el-carousel__item:hover {
  transform: scale(1.02);
  transition: transform 0.3s ease;
  box-shadow: 0 20px 25px -5px rgba(79, 70, 229, 0.1), 0 10px 10px -5px rgba(79, 70, 229, 0.04);
}
</style> 